package com.wzq.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wzq.controller.admin.GetSome;
import com.wzq.dao.dto.Appointmentdto;
import com.wzq.dao.dto.Doordto;
import com.wzq.dao.pojo.*;
import com.wzq.dao.vo.AppointmentVo;
import com.wzq.exception.GlobleExceptionHandler;
import com.wzq.service.IAppointmentService;
import com.wzq.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.wzq.util.AppointmenTextract.getNowLqw;
import static com.wzq.util.AppointmenTextract.getOldLqw;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController extends GetSome {
    @Autowired
    private IAppointmentService iAppointmentService;
    // 申请使用
    @PostMapping("/insert")
    public Result insert(@RequestBody Appointment appointment)   {
        try {
            //  传参是否 有值
            if ("".equals(appointment.getBegin_time()) && "".equals(appointment.getEnd_time()))
                return new Result(Code.SAVE_ERR,false,"请输入正确格式！");
            //region 统一 3种预约时间格式
            if ( appointment.getBegin_time().length()=="yyyy-mm-dd".length()){
                appointment.setBegin_time( appointment.getBegin_time() + " 00:00" );
                appointment.setEnd_time( appointment.getEnd_time() + " 23:59" );
            }else if( appointment.getBegin_time().length()=="yyyy-mm".length()){
                appointment.setBegin_time( appointment.getBegin_time() + "-01 00:00" );
                //结束时间算法
                int i = Integer.parseInt( appointment.getEnd_time().substring( "yyyy-".length() ) ) + 1;
                if (i > 12){ appointment.setEnd_time(Integer.parseInt(appointment.getEnd_time().substring(0,4)) + 1 + "-01-01 00:00");}
                else if (i>9) { appointment.setEnd_time(appointment.getEnd_time().substring(0, 5) + i +"-01 00:00");}
                else             appointment.setEnd_time(appointment.getEnd_time().substring(0, 5) + "0" + i + "-01 00:00");
            }
            //endregion
            iAppointmentService.save(appointment);
        } catch (Exception e){
            return new Result(Code.SAVE_ERR,false,"系统繁忙，插入失败");
        }
        return new Result(Code.SAVE_OK,true);
    }
    //   该设备 该天未结束  的预约时间（时分）   YYYY-MM-dd , p_id , format
    @PostMapping("/hour")
    public Result getByHour(@RequestBody Appointmentdto appointmentdto) {
        // 存入数组
        Integer[] times = {0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0};                  //  时分数组
        // 若为门 则不禁用
        if (Objects.equals(getT_type(iProjectService.getById(appointmentdto.getP_id()).getType()), "门")) {
            return new Result(Code.GET_OK,times);
        }
        String key = appointmentdto.getKey();               //  年月日 2002-08-18
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        try {
            //region 时分判断
            times = getByHour(appointmentdto, times, key, lqw);
        }catch ( Exception e){
            new GlobleExceptionHandler().exceptionHandler(null,e);
            return new Result(Code.GET_ERR,null,"请检查日期格式，系统繁忙！");
        }
        return new Result(Code.GET_OK,times);
    }
    //获取不能使用时间段数组
    private Integer[] getByHour(Appointmentdto appointmentdto, Integer[] times, String key, LambdaQueryWrapper<Appointment> lqw) {
        String[] zancun;
        // 整合   预约时分
        lqw = getNowLqw(appointmentdto, key, lqw,1);
        for (Appointment a : iAppointmentService.list(lqw) ){
            // 将时间区间 以半小时切割     05:30-06:30  —— [ "05:30" , "06:00" , "06:30" ]    12-13-14
            String[] s = DateUtil.getNumber(a.getBegin_time().split(" ")[1]+ "-" +
                    a.getEnd_time().split(" ")[1]);
            // 整合
            for ( String time : s ){
                // 结尾不赋 1
                if ( !time.equals(s[s.length-1]) ){     //  s -> 15:30-16:00
                    zancun = time.split(":");
                    times[ Integer.parseInt(zancun[0]) * 2 + (Integer.parseInt(zancun[1]) == 30 ? 1 : 0) ] = 1;
                }
            }
        }
        // 整合   禁用时分
        for (DisableTime d :   formatAll(key, appointmentdto.getP_id() , 1) ) {
            zancun = d.getDisable_time().split(" ")[1].split("-")[0].split(":");  // "15" , "00"
            times[ Integer.parseInt(zancun[0]) * 2 + (Integer.parseInt(zancun[1]) == 30 ? 1 : 0) ] = 1;
        }
        // endregion
        return times;
    }
    //       该设备 该月份未结束  的预约时间（日）
    @PostMapping("/day")
    public Result getByDay(@RequestBody Appointmentdto appointmentdto) {
        Integer[] days = {0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0};               // 日数组
        // 若为门 则不禁用
        if (Objects.equals(getT_type(iProjectService.getById(appointmentdto.getP_id()).getType()), "门")) {
            return new Result(Code.GET_OK,days);
        }
        String key = appointmentdto.getKey();            // 年月 2002-08
        key = addmonth(key);                                //  月份加1
        List<Appointment> list;                          // 接收 已预约集合
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        try {
            //region 考虑 上一年的按月预约记录是否存在
            lqw = getOldLqw(lqw, appointmentdto, key.substring(0,4),3);
            list = iAppointmentService.list(lqw);
            for (Appointment appointment : list) {
                if ( key.compareTo(appointment.getBegin_time()) > 0 && key.compareTo(appointment.getEnd_time()) <0 )
                    return new Result(Code.GET_OK,days,"该月份已被预约");
            }
            //endregion
            //region  今年 月份判断s
            //该月份是否被预约    模糊查询年份对应预约记录 format=3  该设备该年份的 预约开始和结束时间（月）
            lqw = getNowLqw(appointmentdto ,key.substring(0,4) ,lqw ,3);
            list = iAppointmentService.list(lqw);
            // 判断 该月份是否已被预约     (必须区间判断，因为数据库的日期格式)
            for (Appointment appointment : list) {
                if ( key.compareTo(appointment.getBegin_time().substring(0,"2022-10".length()) ) >= 0 &&
                        key.compareTo(appointment.getEnd_time().substring(0,"2022-10".length()) ) <0 )
                    return new Result(Code.GET_OK,days,"该月份已被预约");
            }
            // 判断 该月份是否被禁用
            if ( formatAll(key.substring(0,"2022-09".length()), appointmentdto.getP_id() ,3).size()>0 )
                return new Result(Code.GET_OK,days,"该月份已被禁用");
            //endregion
            //region 日判断
            //该天是否被预约    模糊查询年月日 对应预约记录  format=2 or 1 该设备该年份的 预约开始和结束时间（日）
            lqw = getNowLqw( appointmentdto , key ,lqw ,1,2);
            list = iAppointmentService.list(lqw);
            // 整合   预约天
            for (Appointment appointment : list) {
                //      按天预约的集合 （区间）
                if (appointment.getFormat()==2){
                    for (int i= Integer.parseInt( appointment.getBegin_time().split(" ")[0].substring("2022-01-".length() ) );
                         i<= Integer.parseInt( appointment.getEnd_time().split(" ")[0].substring( "2022-01-".length() ) ); i++)
                    {
                        days[i-1] = 1;
                    }
                }else       // 某一天的时间段给预约
                    days[ Integer.parseInt( appointment.getBegin_time().split(" ")[0].substring("2022-01-".length() ) )-1 ]= 1 ;
            }
            // 整合   禁用天
            for (DisableTime d: formatAll(key.substring(0,"2022-01".length()) , appointmentdto.getP_id() ,1,2) ){
                days[Integer.parseInt( d.getDisable_time().substring(0, "2022-09-15".length() ).substring("2022-09-".length()) )-1 ] = 1;
            }
            //endregion
        }catch ( Exception e){
            new GlobleExceptionHandler().exceptionHandler(null,e);
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK,days);
    }
    //       该设备 该月份未结束  的预约时间（日）
    @PostMapping("/hour/day")
    public Result getByDayByHour(@RequestBody Appointmentdto appointmentdto) {
        Integer[] days = {0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0,
                          0,0,0,0,0,0,0,0};               // 日数组
        // 若为门 则不禁用
        if (Objects.equals(getT_type(iProjectService.getById(appointmentdto.getP_id()).getType()), "门")) {
            return new Result(Code.GET_OK,days);
        }
        String key = appointmentdto.getKey();            // 年月 2002-08
        key = addmonth(key);                                //  月份加1
        List<Appointment> list;                          // 接收 已预约集合
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        try {
            //region 考虑 上一年的按月预约记录是否存在
            lqw = getOldLqw(lqw, appointmentdto, key.substring(0,4),3);
            list = iAppointmentService.list(lqw);
            for (Appointment appointment : list) {
                if ( key.compareTo(appointment.getBegin_time()) > 0 && key.compareTo(appointment.getEnd_time()) <0 )
                    return new Result(Code.GET_OK,days,"该月份已被预约");
            }
            //endregion
            //region  今年 月份判断
            //该月份是否被预约    模糊查询年份对应预约记录 format=3  该设备该年份的 预约开始和结束时间（月）
            lqw = getNowLqw(appointmentdto ,key.substring(0,4) ,lqw ,3);
            list = iAppointmentService.list(lqw);
            // 判断 该月份是否已被预约     (必须区间判断，因为数据库的日期格式)
            for (Appointment appointment : list) {
                if ( key.compareTo(appointment.getBegin_time().substring(0,"2022-10".length()) ) >= 0 &&
                        key.compareTo(appointment.getEnd_time().substring(0,"2022-10".length()) ) <0 )
                    return new Result(Code.GET_OK,days,"该月份已被预约");
            }
            // 判断 该月份是否被禁用
            if ( formatAll(key.substring(0,"2022-09".length()), appointmentdto.getP_id() ,3).size()>0 )
                return new Result(Code.GET_OK,days,"该月份已被禁用");
            //endregion
            //region 考虑 上一年的按天预约记录是否存在
            lqw = getOldLqw(lqw, appointmentdto, key.substring(0,4),2);
            list = iAppointmentService.list(lqw);
            for (Appointment appointment : list) {
                if ( key.compareTo(appointment.getBegin_time()) > 0 && key.compareTo(appointment.getEnd_time()) <0 )
                    for (int i= 1;
                         i<= Integer.parseInt( appointment.getEnd_time().split(" ")[0].substring( "2022-01-".length() ) ); i++)
                    {
                        days[i-1] = 1;
                    }
            }
            //endregion
            //region 今年 日整合
            //该天是否被预约    模糊查询年月日 对应预约记录  format=2  该设备该年份的 预约开始和结束时间（日）
            lqw = getNowLqw( appointmentdto , key ,lqw ,2);
            list = iAppointmentService.list(lqw);
            // 整合   预约天
            for (Appointment appointment : list) {
                //      按天预约的集合 （区间）
                if (appointment.getFormat()==2){
                    for (int i= Integer.parseInt( appointment.getBegin_time().split(" ")[0].substring("2022-01-".length() ) );
                         i<= Integer.parseInt( appointment.getEnd_time().split(" ")[0].substring( "2022-01-".length() ) ); i++)
                    {
                        days[i-1] = 1;
                    }
                }else       // 某一天的时间段给预约
                    days[ Integer.parseInt( appointment.getBegin_time().split(" ")[0].substring("2022-01-".length() ) )-1 ]= 1 ;
            }
            //endregion
        }catch ( Exception e){
            new GlobleExceptionHandler().exceptionHandler(null,e);
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK,days);
    }
    //       该设备 该月份未结束  的预约时间（日）
    @PostMapping("/month")
    public Result getByMonth(@RequestBody Appointmentdto appointmentdto) {
        // 存入数组
        Integer[] months = {0,0,0,0,0,0
                            ,0,0,0,0,0,0};                // 月数组
        // 若为门 则不禁用
        if ( "门".equals( getT_type(iProjectService.getById(appointmentdto.getP_id()).getType()) )) {
            return new Result(Code.GET_OK,months);
        }
        String key = appointmentdto.getKey();            // 年 2002
        List<Appointment> list;                          // 接收 已预约集合
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        try {
            //region 考虑 上一年的按月预约记录是否存在
            lqw = getOldLqw(lqw, appointmentdto, key,3);
            list = iAppointmentService.list(lqw);
            //进行整合
            for (Appointment a : list){
                for (int i= 1;
                     i <= Integer.parseInt( a.getEnd_time().split(" ")[0].substring( "2022-".length() ,"2022-11".length()) ) -1 ;i++ )
                    months[ i-1 ] = 1;
            }
            //endregion
            //region 今年 的月份整合
            lqw = getNowLqw( appointmentdto, key ,lqw ,3);
            list = iAppointmentService.list(lqw);
            // 预约月整合       需要区间整合
            for (Appointment a : list){
                // 考虑跨年情况
                if (a.getEnd_time().substring(0,"2002".length()).equals(key)){      // 没跨年
                    for (int i= Integer.parseInt( a.getBegin_time().split(" ")[0].substring( "2022-".length() ,"2022-11".length() ) );
                         i <= Integer.parseInt( a.getEnd_time().split(" ")[0].substring( "2022-".length() ,"2022-11".length()) )-1;i++ )
                        months[ i-1 ] = 1;
                }else {                                                             // 跨年
                    for (int i= Integer.parseInt( a.getBegin_time().split(" ")[0].substring( "2022-".length() ,"2022-11".length() ) );
                         i<=12;i++ )
                        months[ i-1 ] = 1;
                }
            }
            // 预约天时分整合
            lqw = getNowLqw( appointmentdto ,key ,lqw ,1,2);
            list = iAppointmentService.list(lqw);
            for (Appointment appointment : list) {
                months[ Integer.parseInt( appointment.getBegin_time().substring( "2022-".length() ,"2022-11".length() ))-1 ] = 1 ;
            }
            //禁用月整合 (包含天时分)
            for (DisableTime disableTime : formatAll(key,appointmentdto.getP_id(),1,2,3)) {
                months[ Integer.parseInt( disableTime.getDisable_time().substring("2022-".length(),"2022-11".length() ) )-1 ] = 1;
            }
            //endregion
        }catch ( Exception e){
            new GlobleExceptionHandler().exceptionHandler(null,e);
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK , months);
    }
    //   修改
    @PutMapping
    public Result update(@RequestBody Appointment actlist) {
        boolean flag = iAppointmentService.updateById(actlist);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    //    删除
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id ) {
        boolean flag = iAppointmentService.removeById(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    //    删除多个id对应用户
    @DeleteMapping
    public Result deleteById(@RequestBody List<Integer> ids) {
        boolean flag = iAppointmentService.removeByIds(ids);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    //     获得所有成员
    @GetMapping
    public Result getAll() {
        List<Appointment> list = iAppointmentService.list();
//        添加用户名称和项目名称
        List<Appointment> appointments=new ArrayList<>();
        for (Appointment a : list) {
            a.setW_name( getW_name(a.getW_id()) );
            a.setP_name( getP_name(a.getP_id()) );
            appointments.add(a);
        }
        Integer code = appointments.size() < 1  ? Code.GET_OK : Code.GET_ERR;
        String msg = appointments.size() < 1 ? "" : "数据查询失败，请重试！";
        return new Result(code,appointments,msg);
    }
    //    多个预约状态
    @PostMapping("/states/{w_id}")
    public Result getstates(@RequestBody List<Integer> p_ids,@PathVariable Integer w_id) throws Exception {
        List<Integer> state=new ArrayList<>();           //存放设备状态   0空闲，1使用中,2我在使用，3禁用,4我的预约中
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        //修改已过期的预约
        appointmentover();
        for (Integer p_id: p_ids ) {
            try {
                lqw.clear();
                // region 查找当前时间是否在使用
                lqw.eq(Appointment::getP_id,p_id).eq(Appointment::getPass,1).eq(Appointment::getIsover,0);
                lqw.gt(Appointment::getEnd_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
                lqw.lt(Appointment::getBegin_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
                Appointment one = iAppointmentService.getOne(lqw);
                // endregion
                if (one!=null)
                state.add( getstate(p_id, w_id,one) );
                else state.add(0);
            } catch (Exception e) {
                new GlobleExceptionHandler().exceptionHandler(null , e);
            }
        }
        Integer code = state.size() > 0 ? Code.GET_OK : Code.GET_ERR;
        String msg = state.size() > 0 ? "" : "数据查询失败，请重试！";
        return new Result(code,state,msg);
    }
    //    单个预约状态
    @GetMapping("/{p_id}/state/{w_id}")
    public Result getstates(@PathVariable Integer p_id,@PathVariable Integer w_id) throws Exception {
        //修改已过期的预约
        appointmentover();
        //存放设备状态   0空闲，1使用中,2我在使用，3禁用,4我的预约中
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        // 判断是否为门
        if ("门".equals( getT_type( iProjectService.getById(p_id).getType()))) {
            // region 查找当前时间是否在使用
            lqw.eq(Appointment::getP_id,p_id).eq(Appointment::getW_id,w_id);
            lqw.eq(Appointment::getIsover,0).eq(Appointment::getPass,1);
            lqw.gt(Appointment::getEnd_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
            lqw.lt(Appointment::getBegin_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
            Appointment one = iAppointmentService.getOne(lqw);
            if (one!=null){
                map.put("state",2);
                one.setW_name(getW_name(w_id));
                map.put("Appointment",one);
            }
        }else {
            try {
                // region 查找当前时间是否在使用
                lqw.clear();
                lqw.eq(Appointment::getP_id,p_id).eq(Appointment::getIsover,0).eq(Appointment::getPass,1);
                lqw.gt(Appointment::getEnd_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
                lqw.lt(Appointment::getBegin_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
                Appointment one = iAppointmentService.getOne(lqw);
                // endregion
                //region 封装 当前的状态 和 使用中的预约记录
                Integer state = getstate(p_id, w_id, one);
                map.put("state",state);
                if (one!=null){
                    one.setW_name(getW_name(one.getW_id()));
                }
                map.put("Appointment",one);
                //endregion
            } catch (Exception e) {
                new GlobleExceptionHandler().exceptionHandler(null , e);
            }
        }
        //region 封装当前已预约情况
        lqw.clear();
        lqw.eq(Appointment::getP_id,p_id).eq(Appointment::getIsover,0).eq(Appointment::getPass,1);
        lqw.gt(Appointment::getBegin_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
        lqw.orderByAsc(Appointment::getBegin_time).last("limit 3");
        List<Appointment> appointments = new ArrayList<>();
        //获取 用户名
        for (Appointment appointment : iAppointmentService.list(lqw)) {
            appointment.setW_name(getW_name(appointment.getW_id()));
            appointments.add(appointment);
        }
        map.put("Appointments",appointments );
        //endregion
        return new Result(Code.GET_OK,map,"获取成功");
    }

    //    预约状态      设备状态   0空闲，1使用中,2我在使用，3已禁用,4我的预约中
    public Integer getstate(Integer p_id, Integer w_id, Appointment one) throws Exception {
        if (one != null) {
            //region 使用 和 在预约中
            if (one.getW_id().equals(w_id)) {
                return 2;
            } else {
                //region 是否在预约中
                LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
                lqw.select(Appointment::getId).eq(Appointment::getPass,1);
                lqw.eq(Appointment::getIsover, 0).eq(Appointment::getPass,1);
                lqw.eq(Appointment::getW_id, w_id).eq(Appointment::getP_id, p_id);
                lqw.gt(Appointment::getBegin_time, DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm"));
                if (iAppointmentService.list(lqw).size() > 0) {
                    return 4;
                }
                //endregion
                return 1;
            }
            //endregion 和
        } else {
            //region   未使用
            // 判断 该月日   是否被禁用
            String now = DateUtil.getCurrentDatePath("YYYY-MM-dd HH:mm");
            if (formatAll(now.substring(0, "2022-09".length()), p_id, 3).size() > 0 ||
                    formatAll(now.substring(0, "2022-09-01".length()), p_id, 2).size() > 0)
                return 3;
            List<DisableTime> disableTimes = formatAll(now.substring(0, "2022-09-01".length()), p_id, 1);
            // 判断当前时分 是否禁用
            if (disableTimes.size() > 1) {
                String year = now.split(" ")[0];                //当前年月日
                String[] timepart;                                  //存放数据库 时间段  用于字符串拼接
                for (DisableTime disableTime : disableTimes) {
                    timepart = disableTime.getDisable_time().split(" ")[1].split("-");
                    if ((year + " " + timepart[0]).compareTo(now) < 0 &&
                            (year + " " + timepart[1]).compareTo(now) > 0)
                        return 3;
                }
            }
            //endregion
        }
        return 0;
    }

    //  是否能申请使用
    @GetMapping("/{w_id}/appointment/{p_id}")
    public Result getAppointment(@PathVariable Integer w_id,@PathVariable Integer p_id) {
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Appointment::getW_id,w_id).eq(Appointment::getP_id,p_id).eq(Appointment::getPass,0).eq(Appointment::getIsover,0);
        if (iAppointmentService.getOne(lqw) != null){
            return new Result(Code.GET_OK, 1);
        }
        return new Result(Code.GET_OK, 0);
    }
    // 获取分段时间
    @GetMapping("/times")
    public Result getTimes()  {
        String[] split = "00:00-23:30".split("-");
        int s=( Integer.parseInt( split[1].substring(0,2) )- Integer.parseInt( split[0].substring(0,2) ) ) *2 +
                ( Integer.parseInt( split[1].substring(3))- Integer.parseInt( split[0].substring(3)) ) /30;
        String[] times = new String[s+1] ;
        int i=0;
        times[i++]= split[0];
        while (!split[0].equals(split[1])){     // 切分20:00-21:30  ->20:00,20:30,21:00,21:30
            if ( !"00".equals(split[0].substring(3))){
                int i1 = Integer.parseInt(split[0].substring(0, 2));
                if (i1+1 <10){
                    split[0] = "0"+(i1+1) + ":00";
                }else   split[0] = i1+1 + ":00";
            }else {
                split[0] = split[0].substring(0,3) + "30";
            }
            times[i++] =split[0];
        }
        String[] timelist=new String[times.length-1];
        for ( int j=0; j<times.length-1 ;j++ )      //  组合
            timelist[j]=times[j]+ "-" +times[j+1];
        Map<String,List<String>> map=new HashMap<>();
        List<String> s1 = new ArrayList<>();
        List<String> s2 = new ArrayList<>();
        for(int n=0; n<timelist.length ; n++){
            if (n%2==0)     s1.add(timelist[n]);
            else    s2.add(timelist[n]);
        }
        map.put("left",s1);
        map.put("right",s2);
        return new Result(Code.GET_OK,map);
    }

    // 统计设备使用记录次数
    @GetMapping("/usecount/{w_id}")
    public Result getCountByPid() throws Exception {
        //region 查询 出类型为资源的id  （资源0）
        List<Type> t_list = iTypeService.list(new LambdaQueryWrapper<Type>().select(Type::getId).eq(Type::getParent, 0));
        List<Integer> type_ids = new ArrayList();
        for (Type type : t_list) {
            type_ids.add(type.getId());
        }
        //endregion
        //region 根据 类型type_ids集合 查询 所有设备id
        if (type_ids==null)
            return new Result(Code.GET_ERR,null,"库中无资源");
        List<Project> plist = iProjectService.list(new LambdaQueryWrapper<Project>().select(Project::getId, Project::getTitle)
                .in(Project::getType, type_ids.toArray()));
        //endregion
        //region 根据用户id 统计所有 资源 使用次数和 时间
        List<AppointmentVo> a_list = new ArrayList<>();
        for (Project project : plist) {
            // 封装 该资源 对象
            AppointmentVo vo = new AppointmentVo();
            // 封装 该月使用天
            Integer[] days = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                   //长度 = 31
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            //  查询该资源 通过的申请 并且 结束时间大于本月份 or 开始时间为本月分
            List<Appointment> list = iAppointmentService.list(new LambdaQueryWrapper<Appointment>().select(Appointment::getBegin_time, Appointment::getEnd_time)
                    .eq(Appointment::getP_id, project.getId()).eq(Appointment::getPass, 1).and((wrapper)->{
                        try {
                            wrapper.ge(Appointment::getBegin_time, DateUtil.getCurrentDatePath("yyyy-MM"))
                                    .or().gt(Appointment::getEnd_time, DateUtil.getCurrentDatePath("yyyy-MM"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }));
            // 用于 判断 预约情况
            int begin=1;
            int end=0;
            int sum=0;
            for (Appointment appointment : list) {
                // 情况1 开始时间小于本月份 结束时间 大于 或 等于 本月份
                if (appointment.getBegin_time().compareTo(DateUtil.getCurrentDatePath("yyyy-MM"))<0 ){
                    begin=1;
                    // end 大于本月份
                    if (appointment.getBegin_time().substring(0,"yyyy-MM".length()).compareTo(DateUtil.getCurrentDatePath("yyyy-MM"))>0)
                        end=Integer.parseInt( DateUtil.getCurrentDatePath("yyyy-MM-dd").substring(8,10));
                    else
                        end = Integer.parseInt( appointment.getEnd_time().substring(8, 10));
                }
                // 情况2 开始时间为本月 结束时间 大于 或 等于 本月
                else if (appointment.getBegin_time().substring(0,"yyyy-MM".length()).compareTo(DateUtil.getCurrentDatePath("yyyy-MM")) ==0 ) {
                    begin = Integer.parseInt( appointment.getBegin_time().substring(8, 10));
                    // 结束时间 大于本月
                    if (appointment.getEnd_time().substring(0,"yyyy-MM".length()).compareTo(DateUtil.getCurrentDatePath("yyyy-MM"))>0)
                        end=Integer.parseInt( DateUtil.getCurrentDatePath("yyyy-MM-dd").substring(8,10));
                    else
                        end = Integer.parseInt( appointment.getEnd_time().substring(8, 10));
                }
                for (int i= begin; i<=end; i++){
                    days[i-1] = 1;
                    sum++;
                }
            }
            int size = list.size();
            vo.setId(project.getId());
            vo.setTitle(project.getTitle());
            vo.setUse_date(days);
            vo.setUse_daysum( sum);
            vo.setBf(300.0 / 31.0 * size);
            a_list.add(vo);
        }
        //endregion
        // 返回
        return  new Result(Code.GET_OK,a_list,"查询成功");
    }

    //预约门接口
    @PostMapping("/door")
    public Result saveDoor(@RequestBody Doordto doordto) {
        boolean flag = iAppointmentService.save(doordto);
        try {
            //  传参是否 有值
            if ("".equals(doordto.getBegin_time()) && "".equals(doordto.getEnd_time()))
                return new Result(Code.SAVE_ERR, false, "请输入正确格式！");
            //region 统一 3种预约时间格式
            if (doordto.getBegin_time().length() == "yyyy-mm-dd".length()) {
                doordto.setBegin_time(doordto.getBegin_time() + " 00:00");
                doordto.setEnd_time(doordto.getEnd_time() + " 23:59");
            } else if (doordto.getBegin_time().length() == "yyyy-mm".length()) {
                doordto.setBegin_time(doordto.getBegin_time() + "-01 00:00");
                //结束时间算法
                int i = Integer.parseInt(doordto.getEnd_time().substring("yyyy-".length())) + 1;
                if (i > 12) {
                    doordto.setEnd_time(Integer.parseInt(doordto.getEnd_time().substring(0, 4)) + 1 + "-01-01 00:00");
                } else if (i > 9) {
                    doordto.setEnd_time(doordto.getEnd_time().substring(0, 5) + i + "-01 00:00");
                } else doordto.setEnd_time(doordto.getEnd_time().substring(0, 5) + "0" + i + "-01 00:00");
            }
            //endregion
            if (flag) {
                Message message = new Message();
                message.setW_id(doordto.getW_id());
                message.setP_id(doordto.getP_id());
                message.setType(4);
                message.setName("管理员");
                iMessageService.save(message);
                return new Result(Code.SAVE_OK, null);
            }
            return new Result(Code.SAVE_ERR, null);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return new Result(Code.SAVE_ERR, null);
    }
    //开门接口
    @GetMapping("{w_id}/openDoor/{p_id}")
    public Result openDoor(@PathVariable Integer w_id, @PathVariable Integer p_id) throws Exception {
        appointmentover();
        LambdaQueryWrapper<Appointment> lqw = new LambdaQueryWrapper<Appointment>();
        lqw.eq(Appointment::getW_id,w_id).eq(Appointment::getP_id,p_id)
                .eq(Appointment::getPass,1).eq(Appointment::getIsover,0).
                le(Appointment::getBegin_time,DateUtil.getCurrentDatePath("yyyy-MM-dd HH:mm"));
        if(iAppointmentService.getOne(lqw)!=null){
            return new Result(Code.GET_OK,null);
        }
        return new Result(Code.GET_ERR,null);
    }

    // 结束使用
    @PutMapping("/{p_id}/over/{w_id}")
    public Result over(@PathVariable Integer w_id,@PathVariable Integer p_id){
        LambdaUpdateWrapper<Appointment> luw = new LambdaUpdateWrapper<>();
        luw.eq(Appointment::getW_id,w_id).eq(Appointment::getP_id,p_id).eq(Appointment::getIsover,0);
        Appointment appointment = new Appointment();
        appointment.setIsover(1);
        return new Result(iAppointmentService.update(appointment,luw)?Code.UPDATE_OK: Code.UPDATE_ERR,null);
    }


}

